﻿using System;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Zxb.DayWork.Core;

namespace Zxb.DayWork.Logic.del
{
    public class ImportEstate
    {
        private static int ImportEstates(NorthSouth ns, int startid, int num)
        {
            DataTable dt = null;
            Database sourcedb = Constant.DicNorthSouth[ns].DataBase;
            string sql = string.Format("select top {0} NID,Newcode,N_or_E,ProjName,LivinDate,Province,City,District,ComArea from proj_info where NID>{1} order by NID", num, startid);
            DbCommand dbCommand = sourcedb.GetSqlStringCommand(sql);
            dt = sourcedb.ExecuteDataSet(dbCommand).Tables[0];

            if (dt == null)
            {
                Logger.InfoLog.Info("没有从新房楼盘表proj_info中读到数据");
                return -1;
            }

            int maxid = 0;
            Database db = DB.ZxbWriter;
            string insertsql = "insert into EstateStatistics (RealEstateID,RealEstateName,CaseAllHits,CaseListHits,IntoTime,Province,City,District,ComArea,NorthSouth,NewHouseRealEstateID) values (@RealEstateID,@RealEstateName,@CaseAllHits,@CaseListHits,@IntoTime,@Province,@City,@District,@ComArea,@NorthSouth,@NewHouseRealEstateID)";
            
            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    DbCommand cmd = db.GetSqlStringCommand(insertsql);
                    db.AddInParameter(cmd, "@RealEstateID", DbType.Int64, (long)dr["Newcode"]);
                    db.AddInParameter(cmd, "@RealEstateName", DbType.String, dr["ProjName"].ToString());
                    db.AddInParameter(cmd, "@CaseAllHits", DbType.Int64, 0L);
                    db.AddInParameter(cmd, "@CaseListHits", DbType.Int64, 0L);
                    db.AddInParameter(cmd, "@IntoTime", DbType.DateTime, (DateTime)dr["LivinDate"]);
                    db.AddInParameter(cmd, "@Province", DbType.String, dr["Province"].ToString());
                    db.AddInParameter(cmd, "@City", DbType.String, dr["City"].ToString());
                    db.AddInParameter(cmd, "@District", DbType.String, dr["District"].ToString());
                    db.AddInParameter(cmd, "@ComArea", DbType.String, dr["ComArea"].ToString());
                    db.AddInParameter(cmd, "@NorthSouth", DbType.String, ns.ToString());
                    db.AddInParameter(cmd, "@NewHouseRealEstateID", DbType.Int32, (int)dr["NID"]);
                    db.ExecuteNonQuery(cmd);
                    if (maxid < (int)dr["NID"])
                    {
                        maxid = (int)dr["NID"];
                    }
                }
                catch (Exception ex)
                {
                    Logger.InfoLog.Error(string.Format("写入数据库失败，丢失记录：{0}，错误：{1}", dr["NID"], ex.Message));
                }
            }
            return maxid;
        }

        private static void UpdateMaxID(string north, int maxid)
        {
            Database db = DB.ZxbWriter;
            string upsql = "update SiteStatus set StatusValue=@StatusValue where StatusName=@StatusName";
            DbCommand upcmd = db.GetSqlStringCommand(upsql);
            db.AddInParameter(upcmd, "@StatusName", DbType.String, north);
            db.AddInParameter(upcmd, "@StatusValue", DbType.Int32, maxid);
            db.ExecuteNonQuery(upcmd);
        }

        private static int ImportAndUpdate(NorthSouth ns, int startid, int num)
        {
            string SiteStatusName = Constant.DicNorthSouth[ns].StatusName;
            
            int maxid = ImportEstates(ns, startid, num);
            if (maxid > 0)
            {
                UpdateMaxID(SiteStatusName, maxid);
            }
            return maxid;
        }

        public static void AutoImport(NorthSouth ns)
        {
            int startid = GetLastID(ns);
            int endid = startid + 1;
            while (startid < endid)
            {
                startid = endid;
                endid = ImportAndUpdate(ns, startid, 1000);
                //Console.WriteLine(ns.ToString() + endid.ToString());
                Zxb.DayWork.Core.Logger.InfoLog.Info(ns.ToString() + endid.ToString());
            }
        }

        public static int GetLastID(NorthSouth ns)
        {
            int result = -1;
            string SiteStatusName = Constant.DicNorthSouth[ns].StatusName;
            Database db = DB.ZxbReader;
            string sql = "SELECT StatusValue from SiteStatus where StatusName=@StatusName";
            DbCommand dbCommand = db.GetSqlStringCommand(sql);
            db.AddInParameter(dbCommand, "@StatusName", DbType.String, SiteStatusName);
            int.TryParse(db.ExecuteScalar(dbCommand).ToString(), out result);
            return result;
        }
    }
}
